package com.bifrost.util;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Properties;

/**
 * Author by yanxiaobo
 * Date on 2018/5/21$.
 */
public class PropertiesUtil {

    private static Logger logger = LoggerFactory.getLogger(PropertiesUtil.class);

    private static Properties props;

    static {
        String fileName = "application-prod.properties";
        props = new Properties();
        try {
            props.load(new InputStreamReader(PropertiesUtil.class.getClassLoader().getResourceAsStream(fileName),"UTF-8"));
        } catch (IOException e) {
            logger.error("配置文件读取异常",e);
        }
    }

    public static String getProperty(String key){
        String value = props.getProperty(key.trim());
        if(StringUtils.isBlank(value)){
            return null;
        }
        return value.trim();
    }

    public static String getProperty(String key,String defaultValue){

        String value = props.getProperty(key.trim());
        if(StringUtils.isBlank(value)){
            value = defaultValue;
        }
        return value.trim();
    }

    public static Integer getInteger(String key) {
    	 String value = props.getProperty(key.trim());
    	 if(StringUtils.isBlank(value)){
             return null;
         }
    	 try {
    		 return Integer.parseInt(value);
    	 } catch(NumberFormatException e) {
    		 logger.error("获取配置失败", e);
    		 return null;
    	 }
    }

    public static Integer getInteger(String key,String defaultValue) {
    	 String value = props.getProperty(key.trim());
    	 if(StringUtils.isBlank(value)){
             value = defaultValue.trim();
         }
    	 try {
    		 return Integer.parseInt(value);
    	 } catch(NumberFormatException e) {
    		 logger.error("获取配置失败", e);
    		 return null;
    	 }
    }

    public static Boolean getBoolean(String key) {
    	 String value = props.getProperty(key.trim());
    	 if(StringUtils.isBlank(value)){
             return null;
         }
    	 try {
    		 return Boolean.parseBoolean(value);
    	 } catch(NumberFormatException e) {
    		 logger.error("获取配置失败", e);
    		 return null;
    	 }
    }
    
    public static Boolean getBoolean(String key,String defaultValue) {
    	 String value = props.getProperty(key.trim());
    	 if(StringUtils.isBlank(value)){
             value = defaultValue.trim();
         }
    	 try {
    		 return Boolean.parseBoolean(value);
    	 } catch(NumberFormatException e) {
    		 logger.error("获取配置失败", e);
    		 return null;
    	 }
    }
    
}
